package com.wiz.web.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wiz.common.Constant;
import com.wiz.common.util.ByteUtil;
import com.wiz.data.factory.MessageDataFactory;
import com.wiz.web.dao.mapper.LoginMapper;
import com.wiz.web.service.LoginService;
import com.wiz.web.vo.to.StationLoginTO;

@Service("loginService")
public class LoginServiceImpl extends BasicServiceImpl implements LoginService,Constant {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private LoginMapper loginMapper;

//	public static void main(String[] args) throws Exception {
//		MessageDataFactory instance = MessageDataFactory.getInstance();
//		String stationMac = "74:27:EA:A7:7A:5C";
//		byte[] bs = instance.getMac(stationMac.getBytes(), ACTIVATE_KEY.getBytes());
//		String staticKey = ByteUtil.Bytes2HexString(bs);
//		System.out.println(staticKey);
//	}
	
	@Override
	public String activateStation(String stationId, String activationCode, String stationMac) throws Exception {
		MessageDataFactory instance = MessageDataFactory.getInstance();
		byte[] bs = instance.getMac(stationMac.getBytes(), ACTIVATE_KEY.getBytes());
		String staticKey = ByteUtil.Bytes2HexString(bs);
		int result = loginMapper.activateStation(stationId, activationCode, stationMac, staticKey);
		if(result > 0){
			log.info("stationId="+stationId+" activating...........success");
			return RESPONSE_CODE_OK;
		}
		log.warn("stationId="+stationId+" activating...........fail");
		return RESPONSE_CODE_ACTIVATE_ERROR;
	}

	@Override
	public String setDynamicKey(String stationId, String dynamicKey) {
		int result = loginMapper.setDynamicKey(stationId, dynamicKey);
		if(result > 0){
			redisManager.set(String.format(STATION_DYNATIC_KEY, stationId), dynamicKey);
			return RESPONSE_CODE_OK;
		}
		return RESPONSE_CODE_DATA_ERROR;
	}

	@Override
	public String getDynamicKey(String stationId) {
		Object o = redisManager.get(String.format(STATION_DYNATIC_KEY, stationId));
		if(o == null){
			StationLoginTO loginTo = loginMapper.getStationLoginTO(stationId);
			return loginTo.getDynamicKey();
		}else{
			return o.toString();
		}
	}

	@Override
	public String getStaticKey(String stationId) {
		StationLoginTO loginTo = loginMapper.getStationLoginTO(stationId);
		return loginTo.getStaticKey();
	}

}
